using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 上下文记忆管理器
    /// </summary>
    public class ContextualMemoryManager
    {
        private readonly ILogger<ContextualMemoryManager> _logger;
        private readonly ConcurrentDictionary<string, Dictionary<string, object>> _contextMemory = new();

        public ContextualMemoryManager(ILogger<ContextualMemoryManager> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 存储上下文记忆
        /// </summary>
        public async Task StoreContextAsync(string contextId, string key, object value)
        {
            try
            {
                _logger.LogDebug($"存储上下文记忆: {contextId}.{key}");
                
                var context = _contextMemory.GetOrAdd(contextId, _ => new Dictionary<string, object>());
                
                lock (context)
                {
                    context[key] = value;
                }
                
                await Task.Delay(1); // 模拟异步操作
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"存储上下文记忆失败: {contextId}.{key}");
                throw;
            }
        }

        /// <summary>
        /// 获取上下文记忆
        /// </summary>
        public async Task<T?> GetContextAsync<T>(string contextId, string key)
        {
            try
            {
                _logger.LogDebug($"获取上下文记忆: {contextId}.{key}");
                
                if (_contextMemory.TryGetValue(contextId, out var context))
                {
                    lock (context)
                    {
                        if (context.TryGetValue(key, out var value) && value is T typedValue)
                        {
                            return typedValue;
                        }
                    }
                }
                
                await Task.Delay(1); // 模拟异步操作
                return default(T);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取上下文记忆失败: {contextId}.{key}");
                throw;
            }
        }

        /// <summary>
        /// 获取整个上下文
        /// </summary>
        public async Task<Dictionary<string, object>> GetFullContextAsync(string contextId)
        {
            try
            {
                _logger.LogDebug($"获取完整上下文: {contextId}");
                
                if (_contextMemory.TryGetValue(contextId, out var context))
                {
                    lock (context)
                    {
                        return new Dictionary<string, object>(context);
                    }
                }
                
                await Task.Delay(1); // 模拟异步操作
                return new Dictionary<string, object>();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取完整上下文失败: {contextId}");
                throw;
            }
        }

        /// <summary>
        /// 清除上下文记忆
        /// </summary>
        public async Task ClearContextAsync(string contextId)
        {
            try
            {
                _logger.LogInformation($"清除上下文记忆: {contextId}");
                
                _contextMemory.TryRemove(contextId, out _);
                
                await Task.Delay(1); // 模拟异步操作
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"清除上下文记忆失败: {contextId}");
                throw;
            }
        }

        /// <summary>
        /// 更新上下文记忆
        /// </summary>
        public async Task UpdateContextAsync(string contextId, Dictionary<string, object> updates)
        {
            try
            {
                _logger.LogDebug($"更新上下文记忆: {contextId}，更新项数: {updates.Count}");
                
                var context = _contextMemory.GetOrAdd(contextId, _ => new Dictionary<string, object>());
                
                lock (context)
                {
                    foreach (var kvp in updates)
                    {
                        context[kvp.Key] = kvp.Value;
                    }
                }
                
                await Task.Delay(1); // 模拟异步操作
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新上下文记忆失败: {contextId}");
                throw;
            }
        }

        /// <summary>
        /// 检查上下文是否存在
        /// </summary>
        public async Task<bool> ContextExistsAsync(string contextId)
        {
            try
            {
                await Task.Delay(1); // 模拟异步操作
                return _contextMemory.ContainsKey(contextId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"检查上下文存在性失败: {contextId}");
                throw;
            }
        }

        /// <summary>
        /// 获取所有上下文ID
        /// </summary>
        public async Task<List<string>> GetAllContextIdsAsync()
        {
            try
            {
                await Task.Delay(1); // 模拟异步操作
                return _contextMemory.Keys.ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有上下文ID失败");
                throw;
            }
        }
    }
}
